package cn.trigram.uuid;

import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.lang3.StringUtils;

/**
 * 每隔一秒都会取最新的资源文件
 */
public class UidConfigHelper {

  private final ResourceBundle resourceBundle;

  public UidConfigHelper(String propertyFileName) {
//		 resourceBundle = ResourceBundle.getBundle( propertyFileName );
    // 每秒取最新属性
    resourceBundle = ResourceBundle
        .getBundle(propertyFileName, Locale.getDefault(), new TimerReloadControl());
  }

  public String getString(String key) {

    if (StringUtils.isBlank(key)) {
      return "";
    }
    return new String(resourceBundle.getString(key).getBytes(StandardCharsets.ISO_8859_1),
        StandardCharsets.UTF_8).trim();
  }

  public int getInt(String key, int defaultValue) {

    int i = 0;
    String str = getString(key);
    if (StringUtils.isBlank(str)) {
      i = defaultValue;
    }
    i = Integer.parseInt(str);
    return i;
  }

  /**
   * 重载控制器
   */
  private static class TimerReloadControl extends ResourceBundle.Control {

    @Override
    public long getTimeToLive(String baseName, Locale locale) {

      return 1000;
    }

    @Override
    public boolean needsReload(String baseName, Locale locale,
        String format, ClassLoader loader, ResourceBundle bundle,
        long loadTime) {

      return true;
    }

  }

}
